package com.qtenv.datasync.job;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.qtenv.datasync.service.model.ZcToSzMeterModel;
import com.qtenv.datasync.service.model.ZcToSzRealtimeModel;
import org.springframework.util.DigestUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ZengChengDataPushJob {
    // 增城水司深圳漏损对接接口
    private static String BASE = "http://nb.intel-water.cn:8080/bmserver";
    // 登录接口
    private static String URL_LOGIN = BASE + "/user/login";
    // 水表添加接口
    private static String URL_ADD_METER = BASE + "/meter/insert";
    // 实时数据接口
    private static String URL_ADD_REALTIME = BASE + "/data/addRealtime;";
    private static String USER_ID = "gdzc";
    private static String DEV_ID = "s15";
    private static String PASSWORD = "123456";
    private static int EXPIRE_DAYS = 6;
    private static Map<String, Object> TOKEN_MAP = new HashMap<>();

    private static void checkAndUpdateTokenMap() {
        boolean loginNeeded = false;
        if (TOKEN_MAP.isEmpty()) {
            loginNeeded = true;
        } else {
            String timestamp = TOKEN_MAP.get("timestamp").toString();
            LocalDateTime expireDate = LocalDateTime.parse(timestamp.substring(0, 19), DatePattern.createFormatter("yyyy-MM-ddTHH:mm:ss")).plusDays(EXPIRE_DAYS);
            if (expireDate.isBefore(LocalDateTime.now())) {
                loginNeeded = true;
            }
        }

        if (loginNeeded) {
            JSONObject loginObject = login().getJSONObject("single");
            TOKEN_MAP.put("clientHash", loginObject.getStr("clientHash"));
            TOKEN_MAP.put("timestamp", loginObject.getStr("timestamp"));//.substring(0, 5)
            TOKEN_MAP.put("devId", DEV_ID);
            TOKEN_MAP.put("userId", USER_ID);
            TOKEN_MAP.put("sessionId", loginObject.getStr("id"));
//            TOKEN_MAP.put("timestamp", DateUtil.format(loginObject.getDate("loginTime"), DatePattern.createFormatter("HH:mm")));
        }

//        String timestamp = DateUtil.format(new Date(), DatePattern.NORM_TIME_FORMAT);
//        String passHash = DigestUtils.md5DigestAsHex(PASSWORD.getBytes());
//        String clientHash = DigestUtils.md5DigestAsHex((passHash + timestamp).getBytes());
//        TOKEN_MAP.put("clientHash", clientHash);
//        TOKEN_MAP.put("timestamp", timestamp);
    }

    private static JSONObject login() {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userId", USER_ID);
        paramMap.put("devId", DEV_ID);

//        String timestamp = DateUtil.format(new Date(), DatePattern.NORM_TIME_FORMAT);
        String timestamp = DateUtil.format(new Date(), "HH:mm");
        String passHash = DigestUtils.md5DigestAsHex(PASSWORD.getBytes());
        String clientHash = DigestUtils.md5DigestAsHex((passHash + timestamp).getBytes());

        paramMap.put("timestamp", timestamp);
        System.out.println("timestamp:" + timestamp);
        paramMap.put("clientHash", clientHash);
        System.out.println("clientHash:" + clientHash);
        System.out.println("login params: " + JSONUtil.toJsonStr(paramMap));
        String result = HttpUtil.createPost(URL_LOGIN).body(JSONUtil.toJsonStr(paramMap)).execute().body();
        System.out.println("login result = " + result);

        JSONObject loginResult = JSONUtil.parseObj(result).getJSONObject("single");
        String newClientHash = DigestUtils.md5DigestAsHex((loginResult.getStr("id") + timestamp + loginResult.getStr("shareSalt")).getBytes());

        result = result.replace("\"single\":{", "\"single\":{\"clientHash\":\"" + newClientHash + "\",\"timestamp\":\"" + timestamp + "\",");
        System.out.println(result);
        return JSONUtil.parseObj(result);
    }

    private static JSONObject addMeterData(ZcToSzMeterModel meterModel) {
        checkAndUpdateTokenMap();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("lr", TOKEN_MAP);
        paramMap.put("single", meterModel);
        System.out.println("add meter params: " + JSONUtil.toJsonStr(paramMap));
        String result = HttpUtil.createPost(URL_LOGIN).body(JSONUtil.toJsonStr(paramMap)).execute().body();
        System.out.println("result=" + result);
        System.out.println(JSONUtil.toJsonStr(result));
        return JSONUtil.parseObj(result);
    }

    private static JSONObject addMeterData(List<ZcToSzMeterModel> meterModelList) {
        checkAndUpdateTokenMap();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("lr", TOKEN_MAP);
        paramMap.put("list", meterModelList);
        String result = HttpUtil.createPost(URL_LOGIN).contentType("application/json").body(JSONUtil.toJsonStr(paramMap)).execute().body();
        System.out.println(JSONUtil.toJsonStr(result));
        return JSONUtil.parseObj(result);
    }

    private static JSONObject addRealtimeData(ZcToSzRealtimeModel realtimeModel) {
        checkAndUpdateTokenMap();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("lr", TOKEN_MAP);
        paramMap.put("single", JSONUtil.toJsonStr(realtimeModel));
        String result = HttpUtil.createPost(URL_LOGIN).contentType("application/json").body(JSONUtil.toJsonStr(paramMap)).execute().body();
        System.out.println(JSONUtil.toJsonStr(result));
        return JSONUtil.parseObj(result);
    }

    private static JSONObject addRealtimeData(List<ZcToSzRealtimeModel> realtimeModelList) {
        checkAndUpdateTokenMap();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("lr", TOKEN_MAP);
        paramMap.put("list", JSONUtil.toJsonStr(realtimeModelList));
        String result = HttpUtil.createPost(URL_LOGIN).contentType("application/json").body(JSONUtil.toJsonStr(paramMap)).execute().body();
        System.out.println(JSONUtil.toJsonStr(result));
        return JSONUtil.parseObj(result);
    }


    public static void main(String[] args) {
        ZcToSzMeterModel testModel = new ZcToSzMeterModel();
        testModel.setId("test-meter-001");
        testModel.setId("20240326174800001");
        testModel.setName("测试水表");
        testModel.setLocation("测试水表测试安装地址");
        testModel.setStealNo("QF00001");
        testModel.setSize("DN15");
        testModel.setExtId("test-meter-001");
        testModel.setModel("测试型号");
        testModel.setDmaId("DMA-001");
        testModel.setFirmId("gdzc");
        testModel.setMeterLoc("POINT(113.77682671 27.99626886)");
        try {
            testModel.setInstallDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2024-03-01 00:00:00"));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        System.out.println(addMeterData(testModel));
    }
}
